<?php

/**
 * 注册
 */

namespace Logic;

use Config\mysql;

class RegistLogic
{
    public static function doRegist($user, $nkName, $pwd)
    {
        $imgUrl = '/avator/default.jpg';
        if ($_FILES['img']['name']) {
            $imgname = $_FILES['img']['name'];
            $tmp = $_FILES['img']['tmp_name'];
            if (!move_uploaded_file($tmp, dirname(__DIR__) . '/Public/avator/' . $imgname)) {
                return ['res' => -1, 'msg' => '头像上传失败!'];
            }
            $imgUrl = '/avator/' . $imgname;
        }

        $dbLink = mysql::mysql();
        $row = $dbLink->query("SELECT uid FROM `tbUser` WHERE username='$user'");
        if ($row->rowCount()) {
            return ['res' => -1, 'msg' => '用户名已存在!'];
        }
        $row = $dbLink->query("SELECT uid FROM `tbUser` WHERE nickname='$nkName'");
        if ($row->rowCount()) {
            return ['res' => -1, 'msg' => '昵称已存在!'];
        }

        $time = date('Y-m-d H:i:s');
        $pass = password_hash($pwd, PASSWORD_BCRYPT, ['cost' => 10]);
        try {
            $dbLink = mysql::mysql();
            $st = $dbLink->prepare(
                'INSERT INTO `tbUser` ( `pwd`,`username`,`nickname`,`avator`,`create_time`,`update_time`) values(:pass,:username,:nk_name,:img_url,:times,:times)'
            );
            $row = $st->execute(
                [
                    ':pass' => $pass,
                    ':username' => $user,
                    ':nk_name' => $nkName,
                    ':img_url' => $imgUrl,
                    ':times' => $time
                ]
            );
            if ($row) {
                return ['res' => 0, 'msg' => '注册成功!'];
            }
        } catch (\PDOException $e) {
            return ['res' => -1, 'msg' => 'Error!' . $e->getMessage()];
        }

        return ['res' => -1, 'msg' => '注册失败!'];
    }
}
